package org.chen.task;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.chen.client.HeyGenClient;
import org.chen.common.utils.SnowflakeIdGenerator;
import org.chen.domain.entity.VideoVoice;
import org.chen.mapper.VoiceMapper;
import org.chen.response.VoiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class VoiceSyncTask {
    @Autowired
    private HeyGenClient heyGenClient;
    
    @Autowired
    private VoiceMapper voiceMapper;

    private static final int BATCH_SIZE = 500; // 每批处理的数据量

    @Scheduled(cron = "0 0 2 * * *")
//    @Scheduled(fixedRateString = "60000")
    @Transactional
    public void syncVoices() {
        log.info("Start syncing voices...");
        try {
            // 1. 获取API数据
            VoiceResponse response = heyGenClient.getVoices();
            if (response == null || response.getData() == null || 
                response.getData().getVoices() == null) {
                log.error("Invalid voice response");
                return;
            }

            List<VoiceResponse.Voice> voices = filterVoicesByLanguage(response);

            // 2. 获取现有数据
            List<String> existingVoiceIds = voiceMapper.selectAllVoiceIds();
            
            // 3. 分类处理
            List<VideoVoice> toInsert = new ArrayList<>();
            List<VideoVoice> toUpdate = new ArrayList<>();
            
            for (VoiceResponse.Voice voice : voices) {
                VideoVoice videoVoice = convertToEntity(voice);
                if (existingVoiceIds.contains(voice.getVoice_id())) {
                    toUpdate.add(videoVoice);
                } else {
                    toInsert.add(videoVoice);
                }
            }

            // 4. 分批处理插入
            if (!toInsert.isEmpty()) {
                Lists.partition(toInsert, BATCH_SIZE).forEach(batch -> {
                    voiceMapper.batchInsert(batch);
                    log.info("Inserted {} voices", batch.size());
                });
            }

            // 5. 分批处理更新
            if (!toUpdate.isEmpty()) {
                Lists.partition(toUpdate, BATCH_SIZE).forEach(batch -> {
                    voiceMapper.batchUpdate(batch);
                    log.info("Updated {} voices", batch.size());
                });
            }

            log.info("Voice sync completed successfully");
        } catch (Exception e) {
            log.error("Voice sync failed", e);
        }
    }

    public List<VoiceResponse.Voice> filterVoicesByLanguage(VoiceResponse response) {
        // 定义需要过滤的语言列表
        List<String> languagesToFilter = List.of(
                "Vietnamese", "Indonesian", "Hindi", "Thai", "Urdu",
                "Arabic", "English", "Malay", "Portuguese"
        );

        // 从响应中获取语音数据并过滤
        // 过滤语言
        // 收集成新的 List

        return response.getData().getVoices().stream()
                .filter(voice -> languagesToFilter.contains(voice.getLanguage()))  // 过滤语言
                .collect(Collectors.toList());
    }
    
    private VideoVoice convertToEntity(VoiceResponse.Voice voice) {
        VideoVoice entity = new VideoVoice();
        // 使用雪花算法生成ID
        entity.setId(SnowflakeIdGenerator.nextId());
        entity.setVoiceId(voice.getVoice_id());
        entity.setLanguage(voice.getLanguage());
        if (voice.getGender().equals("male") || voice.getGender().equals("Male")) {
            entity.setGender("Male");
        }else if (voice.getGender().equals("female") || voice.getGender().equals("Female")) {
            entity.setGender("Female");
        }else {
            entity.setGender("unknown");
        }
        entity.setGender(voice.getGender());
        entity.setName(voice.getName());
        entity.setPreviewAudio(voice.getPreview_audio());
        entity.setSupportPause(voice.getSupport_pause());
        entity.setEmotionSupport(voice.getEmotion_support());
        entity.setSupportInteractiveAvatar(voice.getSupport_interactive_avatar());
        return entity;
    }
}